import { login, logout, getInfo } from '@/api/system/login'
import { setToken, removeToken,setUser, removeUser } from '@/utils/auth'
import { encrypt, decrypt } from '@/utils/jsencrypt'

const user = {
  state: {
  },
  mutations: {
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const tenantCode = userInfo.tenantCode
      return new Promise((resolve, reject) => {
        login(encrypt(username), encrypt(password), encrypt(tenantCode)).then(res => {
            setToken(res.token)
            resolve() //then处理
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const data = res
          if(!data.avatar) data.avatar=require("@/assets/image/profile.jpg"); 
          setUser(data)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      console.log('退出登录')
      return new Promise((resolve, reject) => {
        logout().then((res) => {
          removeToken() // 必须先移除token
          removeUser()
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        removeToken()
        removeUser()
        resolve()
      })
    }
  }
}

export default user